package com.gujiangbo.service.impl;

import com.gujiangbo.constant.IDUtils;
import com.gujiangbo.dao.UserDaoService;
import com.gujiangbo.entity.AcctUsers;
import com.gujiangbo.request.QueryUser;
import com.gujiangbo.request.UpdateUser;
import com.gujiangbo.request.UpdateUserRequest;
import com.gujiangbo.request.UserInVo;
import com.gujiangbo.response.UserOutVo;
import com.gujiangbo.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.IntStream;

@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserDaoService userDaoService;

    @Override
    public UserOutVo queryUser(UserInVo userInVo) {
        UserOutVo userOutVo = new UserOutVo();
        AcctUsers acctUsers = userDaoService.queryUser(userInVo);
        userOutVo.setAcctUsers(acctUsers);
        return userOutVo;
    }

    @Override
    public void batchUsers() {
        int batchSize = 3000;
        AtomicInteger atomicInteger = new AtomicInteger();
        List<AcctUsers> list = new ArrayList<>();
        IntStream.range(0, 3000).forEach(i -> {
            AcctUsers user = new AcctUsers();
            user.setUId(IDUtils.getId());
            user.setUName(IDUtils.getRandomName());
            user.setUAddr(IDUtils.getRandomAddress());
            user.setUTms(new Date());
            user.setUMobile(IDUtils.getTel());
            list.add(user);
            atomicInteger.incrementAndGet();
        });
        userDaoService.batchUsers(list, batchSize);
    }

    @Override
    public boolean updateUser(UpdateUserRequest updateUserRequest) {
        QueryUser queryUser = updateUserRequest.getQueryUser();
        UpdateUser updateUser = updateUserRequest.getUpdateUser();
        String id = queryUser.getId();
        UserInVo userInVo = new UserInVo();
        userInVo.setId(id);
        AcctUsers acctUsers = userDaoService.queryUser(userInVo);
        if (ObjectUtils.isEmpty(acctUsers)) {
            return false;
        }

        Optional.ofNullable(updateUser.getAddress()).ifPresent(acctUsers::setUAddr);
        Optional.ofNullable(updateUser.getMobile()).ifPresent(acctUsers::setUMobile);
        Optional.ofNullable(updateUser.getName()).ifPresent(acctUsers::setUName);
        acctUsers.setUTms(new Date());
        return userDaoService.updateByID(acctUsers);
    }

    @Override
    public AcctUsers queryUsersByMobiles(String requestMap) {
        return userDaoService.queryUsersByMobiles(requestMap);
    }
}
